#!/bin/bash

# =============================================================================
# 数据库配置脚本
# =============================================================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 数据库配置
DB_NAME="memebot"
DB_USER="memebot_user"

log_info "开始数据库配置..."

# 安装PostgreSQL
log_info "安装PostgreSQL..."
if ! command -v psql &> /dev/null; then
    sudo apt install -y postgresql postgresql-contrib
    sudo systemctl start postgresql
    sudo systemctl enable postgresql
    log_success "PostgreSQL 安装完成"
else
    log_info "PostgreSQL 已安装"
fi

# 生成随机密码
DB_PASSWORD=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
log_info "生成数据库密码: $DB_PASSWORD"

# 创建数据库和用户
log_info "创建数据库和用户..."
sudo -u postgres psql << EOF
-- 删除已存在的数据库和用户（如果存在）
DROP DATABASE IF EXISTS $DB_NAME;
DROP USER IF EXISTS $DB_USER;

-- 创建新的数据库和用户
CREATE DATABASE $DB_NAME;
CREATE USER $DB_USER WITH ENCRYPTED PASSWORD '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;
ALTER USER $DB_USER CREATEDB;

-- 连接到数据库并授权
\c $DB_NAME
GRANT ALL ON SCHEMA public TO $DB_USER;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO $DB_USER;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO $DB_USER;

\q
EOF

# 配置PostgreSQL
log_info "配置PostgreSQL..."
PG_VERSION=$(sudo -u postgres psql -t -c "SELECT version();" | grep -oP 'PostgreSQL \K[0-9]+')
PG_CONFIG_DIR="/etc/postgresql/$PG_VERSION/main"

# 备份原配置
sudo cp $PG_CONFIG_DIR/postgresql.conf $PG_CONFIG_DIR/postgresql.conf.backup
sudo cp $PG_CONFIG_DIR/pg_hba.conf $PG_CONFIG_DIR/pg_hba.conf.backup

# 配置监听地址
sudo sed -i "s/#listen_addresses = 'localhost'/listen_addresses = 'localhost'/" $PG_CONFIG_DIR/postgresql.conf

# 重启PostgreSQL
sudo systemctl restart postgresql

# 测试数据库连接
log_info "测试数据库连接..."
if PGPASSWORD=$DB_PASSWORD psql -h localhost -U $DB_USER -d $DB_NAME -c "SELECT version();" > /dev/null 2>&1; then
    log_success "数据库连接测试成功"
else
    log_error "数据库连接测试失败"
    exit 1
fi

# 保存数据库配置到文件
cat > /tmp/db_config.env << EOF
# 数据库配置信息
DB_NAME=$DB_NAME
DB_USER=$DB_USER
DB_PASSWORD=$DB_PASSWORD
DATABASE_URL="postgresql://$DB_USER:$DB_PASSWORD@localhost:5432/$DB_NAME"
EOF

log_success "数据库配置完成！"
log_info "数据库配置信息已保存到 /tmp/db_config.env"
log_warning "请妥善保存数据库密码: $DB_PASSWORD"
